import { Login } from "@/api/login";
import { getToken, setToken, getUserId ,setUserId, getNickname, setNickname } from "@/utils/app.js";

const state = {
  token: '' || getToken(),
  userid: '' || getUserId(),
  nickname: '' || getNickname()
}
const getters = {
  // 多为计算属性
  token: (state) => state.token,
  userid: (state) => state.userid
}
const mutations = { // 没有回调
  //  修改值
  SET_TOKEN(state, token) {
    state.token = token;
  },
  SET_USERID(state, userid) {
    state.userid = userid;
  },
  SET_NICKNAME(state, nickname) {
    state.nickname = nickname;
  }
}
const actions = { // 可以回调  多为业务方法
  login(content, data) {
    return new Promise((resolve, reject) => {
      // 接口
      Login(data).then((rep) => {
        console.log("login=======rep",rep)

        // content 就是 拿到所有
        let data = rep.data.message;
        console.log(data);


        let info = data.userInfo;
        console.log(info, "=====info===")

        content.commit("SET_TOKEN", data.token);
        content.commit("SET_USERID", info.id );

        content.commit("SET_NICKNAME", info.nickname);
        setToken(data.token);
        setUserId(info.id);
        setNickname(info.nickname);

        return resolve(rep);
      }).catch(err => {
        return reject();
      })
    })
  }
}


export default {
  snamespaced: true,  // 使用命名空间  app/方法
  state,
  getters,
  mutations,
  actions
};